<template>
	<div>
		<el-card>
			<el-form :model="state.pageParam.param" label-width="120" ref="queryFormRef" @keyup.enter.native="loadList">
			    <el-row>
			        <el-col :xs="3" :sm="4" :md="6" :lg="8" :xl="8">
			            <el-form-item prop="setCode" label="数据集编码">
			                <el-input v-model="state.pageParam.param.setCode" placeholder="数据集编码" clearable>
                            </el-input>
                        </el-form-item>
                    </el-col>
			        <el-col :xs="3" :sm="4" :md="6" :lg="8" :xl="8">
			            <el-form-item prop="setName" label="数据集名称">
			                <el-input v-model="state.pageParam.param.setName" placeholder="数据集名称" clearable>
                            </el-input>
                        </el-form-item>
                    </el-col>
			        <el-col :xs="3" :sm="4" :md="6" :lg="8" :xl="8">
			            <el-form-item prop="sourceCode" label="数据源">
                            <DicSelect v-model="state.pageParam.param.sourceCode" placeholder="请选择" :customData="state.dataSourceOptions" style="width:100%"></DicSelect>
                        </el-form-item>
                    </el-col>
			        <el-col :xs="3" :sm="4" :md="6" :lg="8" :xl="8">
			            <el-form-item prop="enableFlag" label="是否启用">
			                <DicSelect v-model="state.pageParam.param.enableFlag" placeholder="请选择" dicCode="1008" style="width:100%"></DicSelect>
                        </el-form-item>
                    </el-col>
			        <el-col :xs="3" :sm="4" :md="6" :lg="8" :xl="8">
			            <el-form-item prop="deleteFlag" label="是否删除">
			                <DicSelect v-model="state.pageParam.param.deleteFlag" placeholder="请选择" dicCode="1008" style="width:100%"></DicSelect>
                        </el-form-item>
                    </el-col>
			        <el-col :xs="3" :sm="4" :md="6" :lg="8" :xl="8">
			            <el-form-item prop="setType" label="数据集类型">
                            <DicSelect v-model="state.pageParam.param.setType" placeholder="请选择" dicCode="REPORT_DATASET_TYPE" style="width:100%"></DicSelect>
                        </el-form-item>
                    </el-col>
                </el-row>
			</el-form>
            <div class="btnSearchStyle">
                <el-button type="primary" class="ml7" @click="loadList">
                    <el-icon>
                        <ele-Search />
                    </el-icon>
                    查询
                </el-button>
                <el-button type="primary" class="ml10" @click="reSetForm(queryFormRef)">
                    <el-icon>
                        <ele-Refresh />
                    </el-icon>
                    重置
                </el-button>
            </div>
        </el-card>
        <el-card>
            <div class="btnStyle">
                <el-dropdown @command="addOrUpdateHandle">
                    <el-button  type="success" icon="ele-Plus">
                        新增
                        <el-icon class="el-icon--right"><arrow-down /></el-icon>
                    </el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item command="sql">SQL</el-dropdown-item>
                            <el-dropdown-item command="http">HTTP</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </div>
            <el-table :data="state.dataList" style="width: 100%">
                <el-table-column prop="setCode" header-align="center" align="center" label="数据集编码"/>
                <el-table-column prop="setName" header-align="center" align="center" label="数据集名称"/>
                <el-table-column prop="setDesc" header-align="center" align="center" label="数据集描述"/>
                <el-table-column prop="sourceCode" header-align="center" align="center" label="数据源编码"/>
                <el-table-column prop="setType" header-align="center" align="center" label="数据集类型" column-key="REPORT_DATASET_TYPE" :formatter="formatStatus"/>
                <el-table-column prop="enableFlag" header-align="center" align="center" label="是否启用" column-key="1008" :formatter="formatStatus"/>
                <el-table-column prop="deleteFlag" header-align="center" align="center" label="是否删除" column-key="1008" :formatter="formatStatus"/>
                <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
                    <template #default="scope">
                        <el-button type="primary" link  @click="updateHandle(scope.row)" >修改</el-button>
                        <el-button type="primary" link  @click="deleteHandle(scope.row.id)"  >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="onHandleSizeChange"
                @current-change="onHandleCurrentChange"
                :pager-count="5"
                :page-sizes="[10, 50, 200]"
                v-model:current-page="state.pageParam.page"
                background
                v-model:page-size="state.pageParam.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="state.total" small>
            </el-pagination>
        </el-card>
        <el-dialog width="80%" :close-on-click-modal="false" :title="!state.submitForm.id ? '新增' : '修改'" ref="addOrUpdate" v-model="state.addOrUpdateVisible">
            <el-form :model="state.submitForm" :rules="state.submitFormRule" ref="ruleFormRef" @keyup.enter.native="dataFormSubmit(ruleFormRef)" label-width="120px">
                <el-row v-if="state.submitForm.setType=='sql'">
                    <el-col :span="24">
                        <el-form-item label="数据源" prop="sourceCode">
                            <DicSelect v-model="state.submitForm.sourceCode" placeholder="请选择" :customData="state.dataSourceOptions" style="width:100%"></DicSelect>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="数据集编码" prop="setCode">
                            <el-input v-model="state.submitForm.setCode" placeholder="数据集编码" maxlength="50"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="数据集名称" prop="setName">
                            <el-input v-model="state.submitForm.setName" placeholder="数据集名称" maxlength="100"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="数据集描述" prop="setDesc">
                            <el-input v-model="state.submitForm.setDesc" placeholder="数据集描述" maxlength="255"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="state.submitForm.setType=='sql'">
                    <el-col :span="24">
                        <el-form-item label="查询SQL" prop="dynSentence">
                            <MonacoEditor v-model.trim="state.submitForm.dynSentence" language="sql" style="height: 300px"></MonacoEditor>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="state.submitForm.setType=='http'">
                    <el-col :span="24">
                        <el-form-item label="请求路径" prop="apiUrl">
                            <el-input v-model="state.submitForm.apiUrl" placeholder="请求路径" maxlength="500">
                                <template #prepend>
                                    <DicSelect v-model="state.submitForm.method" placeholder="请选择" dicCode="HTTP_METHOD" style="width:100%"></DicSelect>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="state.submitForm.setType=='http'">
                    <el-col :span="24">
                        <el-form-item label="请求头" prop="header">
                            <el-input v-model="state.submitForm.header" placeholder="请求头" maxlength="500"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="state.submitForm.setType=='http'">
                    <el-col :span="24">
                        <el-form-item label="请求体" prop="body">
                            <el-input v-model="state.submitForm.body" placeholder="请求体" maxlength="1000"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-tabs type="border-card" v-model.trim="state.tabsActiveName">
                            <el-tab-pane label="查询参数" name="first">
                                <el-button v-if="state.tableData.length == 0" type="text" size="small" @click="addRow()">添加
                                </el-button>
                                <el-table :data="state.tableData" border style="width: 100%">
                                    <el-table-column align="center" label="序号" type="index" min-width="50"/>
                                    <el-table-column label="参数名" align="center">
                                        <template #default="scope">
                                            <el-input
                                                v-model.trim="state.tableData[scope.$index].paramName"
                                                :disabled="
                                                    state.tableData[scope.$index].paramName == 'pageSize' ||
                                                    state.tableData[scope.$index].paramName == 'pageNumber'
                                                "/>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="描述" align="center">
                                        <template #default="scope">
                                            <el-input v-model.trim="state.tableData[scope.$index].paramDesc" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="数据类型" align="center">
                                        <template #default="scope">
                                            <el-input v-model.trim="state.tableData[scope.$index].paramType" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="示例值" align="center">
                                        <template #default="scope">
                                            <el-input v-model.trim="state.tableData[scope.$index].sampleItem" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="校验" width="250" align="center">
                                        <template #default="scope">
                                            <el-checkbox v-model="state.tableData[scope.$index].mandatory"
                                                @change="Mandatory(scope.$index)" >必选
                                            </el-checkbox> &NonBreakingSpace;
                                            <el-button type="primary" icon="el-icon-plus" @click="permissionClick(scope.row, scope.$index)">
                                            高级规则
                                            </el-button>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="操作" width="200" align="center">
                                        <template #default="scope">
                                            <el-button type="primary" link size="small"
                                                @click.native.prevent="
                                                    cutOutRow(scope.$index, state.tableData)
                                                "
                                            >删除
                                            </el-button>
                                            <el-button type="primary" link size="small"
                                                @click="addRow()"
                                            >追加
                                            </el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </el-tab-pane>
                            <el-tab-pane label="数据转换" name="second">Config</el-tab-pane>
                            <el-tab-pane label="测试预览" name="third">Role</el-tab-pane>
                        </el-tabs>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="state.addOrUpdateVisible = false">取消</el-button>
                    <el-button type="primary" @click="dataFormSubmit(ruleFormRef)">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts" name="reportDataSet">
import { ElMessage, ElMessageBox, FormInstance, ElLoading } from 'element-plus'
import { ref, reactive, onMounted, watch, defineAsyncComponent } from 'vue'
import { ArrowDown } from '@element-plus/icons-vue'
import { reportApi } from '/@/api/sys/report-api'
import { getDataDictionaryList } from '/@/utils/cacheDic'
import { number } from 'echarts'
const MonacoEditor = defineAsyncComponent(() => import('/@/components/MonacoEditor/index.vue'))
const queryFormRef = ref<FormInstance>()
const ruleFormRef = ref<FormInstance>()
const state = reactive({
    listLoading: false,
    total: 0,
    dataList: [],
    dataListSelections: [],
    dataDictionaryList: {} as any,
    dataSourceOptions: [],
    pageParam: {
        page: 1,
        pageSize: 10,
        param: {
            id: '',
            setCode: '',
            setName: '',
            setDesc: '',
            sourceCode: '',
            dynSentence: '',
            caseResult: '',
            enableFlag: '',
            deleteFlag: '',
            createBy: '',
            createTime: '',
            updateBy: '',
            updateTime: '',
            version: '',
            setType: '',
        }
    },
    addOrUpdateVisible: false,
    submitForm: {
            id: '',
            setCode: '',
            setName: '',
            setDesc: '',
            sourceCode: '',
            dynSentence: '',
            caseResult: '',
            enableFlag: '',
            deleteFlag: '',
            createBy: '',
            createTime: '',
            updateBy: '',
            updateTime: '',
            version: '',
            setType: '',
            apiUrl: '',
            method: 'GET',
            header: '{"Content-Type":"application/json;charset=UTF-8"}',
            body: '',
    },
    submitFormRule: {
        sourceCode: { required: false, message: '数据源不能为空', trigger: 'blur' },
        setCode: { required: true, message: '数据集编码不能为空', trigger: 'blur' },
        setName: { required: true, message: '数据集名称不能为空', trigger: 'blur' },
    },
    tabsActiveName: 'first',
    tableData: [] as any,
    title: '自定义高级规则',
    isRowData: {} as any,
    validationRules: '',
    dialogPermissionVisible: false,
    itemFilterList: [
        {
            transformType: "js",
            transformScript: ``
        }
    ],
})
const loadList = () => {
    state.listLoading = true
    reportApi.queryReportDataSetListPage(state.pageParam).then(data => {
        if (data && data.code === 0) {
            state.dataList = data.data.records
            state.total = data.data.totalRow
        } else {
            state.dataList = []
            state.total = 0
        }
    }).catch(() => {
    }).finally(() => {
        state.listLoading = false
    })
}
// 页面加载时
onMounted(() => {
    // 数据字典
	getDataDictionaryList(state.dataDictionaryList, ['1008', 'REPORT_DATASET_TYPE'])
    reportApi.getDataSourceSelect().then(data => {
        if (data && data.code === 0) {
            state.dataSourceOptions = data.data
        }
    })
    // 列表查询
    loadList()
})
watch(() => state.submitForm.setType, (val:string) => {
	if (val == 'sql') {
		state.submitFormRule.sourceCode.required = true
	}else{
		state.submitFormRule.sourceCode.required = false
	}
})
//重置
const reSetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    state.pageParam.page = 1
    loadList()
}
// 分页改变
const onHandleSizeChange = (val: number) => {
    state.pageParam.pageSize = val;
    loadList()
}
// 分页改变
const onHandleCurrentChange = (val: number) => {
    state.pageParam.page = val;
    loadList()
}
//删除
const deleteHandle = (id: string | undefined) => {
    if(!id) {
        ElMessage.error('请选择记录！')
        return
    }
    ElMessageBox.confirm('是否确定删除所选记录', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
    }).then(() => {
        reportApi.deleteReportDataSetInfo(id).then(data => {
            if (data && data.code === 0) {
                ElMessage.success('删除成功')
                loadList()
            } else {
                ElMessage.error(data.message)
            }
        }).catch(() => {
            ElMessage.error("删除失败")
        })
    })
}
//打开新增弹窗
const addOrUpdateHandle = (command: string) => {
    state.submitForm = {
            id: '',
            setCode: '',
            setName: '',
            setDesc: '',
            sourceCode: '',
            dynSentence: '',
            caseResult: '',
            enableFlag: '',
            deleteFlag: '',
            createBy: '',
            createTime: '',
            updateBy: '',
            updateTime: '',
            version: '',
            setType: '',
            apiUrl: '',
            method: 'GET',
            header: '{"Content-Type":"application/json;charset=UTF-8"}',
            body: '',
    }
    state.submitForm.setType = command
    state.addOrUpdateVisible = true
}
//打开修改弹窗
const updateHandle = (row: any | undefined) => {
    state.submitForm = {
            id: row.id,
            setCode: row.setCode,
            setName: row.setName,
            setDesc: row.setDesc,
            sourceCode: row.sourceCode,
            dynSentence: row.dynSentence,
            caseResult: row.caseResult,
            enableFlag: row.enableFlag,
            deleteFlag: row.deleteFlag,
            createBy: row.createBy,
            createTime: row.createTime,
            updateBy: row.updateBy,
            updateTime: row.updateTime,
            version: row.version,
            setType: row.setType,
            apiUrl: row.apiUrl,
            method: row.method,
            header: row.header,
            body: row.body,
    }
    state.addOrUpdateVisible = true
}
//新增修改提交
const dataFormSubmit = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid: boolean) => {
        if (valid) {
            //提交数据
            const loading = ElLoading.service({
                lock: true,
                text: '处理中',
                background: 'rgba(0, 0, 0, 0.7)',
            })
            if(!state.submitForm.id) {
                //新增
                reportApi.saveReportDataSetInfo(state.submitForm).then(data => {
                    if (data && data.code === 0) {
                        ElMessage.success('保存成功')
                        state.addOrUpdateVisible = false
                        loadList()
                    } else {
                        ElMessage.error(data.message)
                    }
                }).catch(() => {
                    ElMessage.error('保存失败')
                }).finally(() => {
                    loading.close()
                })
            }else{
                reportApi.updateReportDataSetInfo(state.submitForm).then(data => {
                    if (data && data.code === 0) {
                        ElMessage.success('保存成功')
                        state.addOrUpdateVisible = false
                        loadList()
                    } else {
                        ElMessage.error(data.message)
                    }
                }).catch(() => {
                    ElMessage.error('保存失败')
                }).finally(() => {
                    loading.close()
                })
            }
        }
    })
}
const formatStatus = (row: any, column: any, cellValue: string | number, index: number) => {
	if(Object.keys(state.dataDictionaryList).length>0){
		if (cellValue) {
			return state.dataDictionaryList[column.columnKey].get(cellValue);
		}
	}
}

//参数添加行
const addRow = () => {
    state.tableData.push({
        paramName: '',
        paramDesc: '',
        paramType: '',
        sampleItem: '',
        mandatory: true,
        requiredFlag: 1,
        validationRules: `function verification(data){\n\t//自定义脚本内容\n\t//可返回true/false单纯校验键入的data正确性\n\t//可返回文本，实时替换,比如当前时间等\n\t//return "2099-01-01 00:00:00";\n\treturn true;\n}`
      })
}

// 必选
const Mandatory = (val: number) => {
    if (!state.tableData[val].mandatory) {
        state.tableData[val].requiredFlag = 0;
    } else {
        state.tableData[val].requiredFlag = 1;
    }
}
// --查询参数高级规则
const permissionClick = (row: any, index: number) => {
    state.title = "自定义高级规则";
    if (state.isRowData.sampleItem != "") {
    state.isRowData = row;
    const fnCont = `function verification(data){\n\t//自定义脚本内容\n\t//可返回true/false单纯校验键入的data正确性\n\t//可返回文本，实时替换,比如当前时间等\n\t//return "2099-01-01 00:00:00";\n\treturn true;\n}`;
    state.validationRules = row.validationRules
        ? row.validationRules
        : fnCont;
    }
    state.dialogPermissionVisible = true;
}
// 删除
const cutOutRow = (index: number, rows: any) => {
    rows.splice(index, 1);
}
</script>